package com.huang.springbootjspshiro.controller;

import com.huang.springbootjspshiro.bean.User;
import com.huang.springbootjspshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;




    @RequestMapping("logout")
    public String logout(){
        //获取登录的主体  点击登录了就能拿到
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    @RequestMapping("login")
    public String login(String username, String pwd, String code1){
            try {
                if("1234"
                .equals(code1)){
                    Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username,pwd));
                return "redirect:/index.jsp";
            }else{
                throw new RuntimeException("验证码出错");
            }


        } catch (UnknownAccountException e) {
                e.printStackTrace();
                System.out.println("用户名错误");
            }catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                System.out.println("密码错误");
            }

        return "redirect:/login.jsp";
    }
    @RequestMapping("register")
    public String register(User user){
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }

    }

}
